package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/lib/geetest"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
)

type TestAPI struct {
}

func (a TestAPI) Name() string {
	return "test API"
}

func (a TestAPI) Bind() {
	testAPI := config.C.Router.Group("/v1/data")
	{
		testAPI.GET("study/test", Test)
		testAPI.GET("study/testNode", TestNode)
	}
	test1API := config.C.Router.Group("/test/")
	{
		test1API.GET("geet", geetInit)
		test1API.GET("login", testlogin)
		test1API.POST("validate", geetValidate)
	}
}


func Test(c *gin.Context) {

	// 参数校验
	var params model.FormatParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	var logOut []string
	logOut = append(logOut, "2019-12:15 01:01:00", "测试第1个日志、")
	logOut = append(logOut, "测试第2个日志、")
	logOut = append(logOut, "测试第3个日志、")
	logOut = append(logOut, "测试第4个日志、")
	logOut = append(logOut, "测试第5个日志、")

	//redisKey := "111"
	//if redis.Exists(redisKey) {
	//	re, err := redis.Get(redisKey)
	//	if err != nil {
	//		e.LogParams("err", params, "redis get error")
	//	}
	//	e.LogParams("info", params, "redis exists key: ", re)
	//}

	LogParams("info", params, logOut)
	api.SendResponse(c, errno.OK, nil)
}

func TestNode(c *gin.Context) {

	//phone := c.Query("phone")
	data := "Yes"
	//if !IsPhone(phone) {
	//	data = "No"
	//}
	api.SendResponse(c, errno.OK, data)
}

const page1 = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>gt-php-sdk-demo</title>
    <style>
        body {
            margin: 50px 0;
            text-align: center;
        }
        .inp {
            border: 1px solid gray;
            padding: 0 10px;
            width: 200px;
            height: 30px;
            font-size: 18px;
        }
        .btn {
            border: 1px solid gray;
            width: 100px;
            height: 30px;
            font-size: 18px;
            cursor: pointer;
        }
        #embed-captcha {
            width: 300px;
            margin: 0 auto;
        }
        .show {
            display: block;
        }
        .hide {
            display: none;
        }
        #notice {
            color: red;
        }
    </style>
</head>
<body>
<h1>极验验证SDKDemo</h1>
<form class="popup" action="validate" method="post">
    <h2>嵌入式Demo，使用表单形式提交二次验证所需的验证结果值</h2>
    <br>
    <p>
        <label for="username2">用户名：</label>
        <input class="inp" id="username2" type="text" value="极验验证">
    </p>
    <br>
    <p>
        <label for="password2">密&nbsp;&nbsp;&nbsp;&nbsp;码：</label>
        <input class="inp" id="password2" type="password" value="123456">
    </p>

    <div id="embed-captcha"></div>
    <p id="wait" class="show">正在加载验证码......</p>
    <p id="notice" class="hide">请先完成验证</p>

    <br>
    <input class="btn" id="embed-submit" type="submit" value="提交">
</form>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>
<script src="/static/js/gt.js"></script>
<script>
    var handlerEmbed = function (captchaObj) {
        $("#embed-submit").click(function (e) {
            var validate = captchaObj.getValidate();
            if (!validate) {
                $("#notice")[0].className = "show";
                setTimeout(function () {
                    $("#notice")[0].className = "hide";
                }, 2000);
                e.preventDefault();
            }
        });
        // 将验证码加到id为captcha的元素里，同时会有三个input的值：geetest_challenge, geetest_validate, geetest_seccode
        captchaObj.appendTo("#embed-captcha");
        captchaObj.onReady(function () {
            $("#wait")[0].className = "hide";
        });
        // 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
    };
    $.ajax({
        // 获取id，challenge，success（是否启用failback）
        url: "http://127.0.0.1:8080/test/geet?t=" + (new Date()).getTime(), // 加随机数防止缓存
        type: "get",
        dataType: "json",
        success: function (data) {
            console.log(data);
            // 使用initGeetest接口
            // 参数1：配置参数
            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                new_captcha: data.new_captcha,
                product: "embed", // 产品形式，包括：float，embed，popup。注意只对PC版验证码有效
                offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handlerEmbed);
        }
    });
</script>
</body>
</html>`

func geetInit(c *gin.Context) {
	response := geetest.GeetestInit(c, "web")

	c.JSON(200, response)
}

func testlogin(c *gin.Context) {
	c.Header("Content-Type", "text/html; charset=utf-8")

	c.String(200, page1)

}

func geetValidate(c *gin.Context) {
	response, _ := geetest.Validate(c, geetest.ClientTypeAPP)
	c.JSON(200, response)

}
